import React, {useEffect, useState} from "react";
import {createStyles} from "antd-style";
import {Button, Popover, Spin, Switch} from "antd";
import {FbTypes} from "@/pages/FbPage/BucketViewer";
import FileBucketApi, {FbInfo} from "@/api/web/FileBucketApi.ts";
import {useNavigate, useSearchParams} from "react-router";
import useAppState from "@/store/AppState.ts";
import FileBucketInfoModal from "@/pages/FbPage/BucketHeader/FileBucketInfoModal.tsx";

export const bucketHeaderHeight = 48

const useStyles = createStyles(({css, token}) => {
    return {
        container: css`
            display: flex;
            position: fixed;
            left: 0;
            top: 0;
            width: 100%;
            height: ${bucketHeaderHeight}px;
            align-items: center;
            background-color: ${token.colorBgContainer}af;
            text-wrap: nowrap;
            z-index: 100;
            overflow: auto;
            gap: 8px;
            padding: 0 10px;
        `,
        popoverBtn: css`
            display: block;
            width: 100%;
            text-align: left;
            text-wrap: nowrap;
            font-size: 15px;
            line-height: 15px;
            padding: 8px 12px;
            color: ${token.colorText};
            border-radius: ${token.borderRadiusSM}px;

            :hover {
                color: ${token.colorPrimary};
            }
        `,
        popoverBtnActive: css`
            background-color: ${token.colorPrimaryActive};
        `,
        popoverContent: css`
            max-height: 500px;
            overflow: auto;
        `,
    }
})

interface Props {
    fbInfo: FbInfo,
    rerenderTrigger?: () => void
}

const BucketHeader: React.FC<Props> = ({fbInfo, rerenderTrigger}) => {
    const width = useAppState(state => state.width);
    const styles = useStyles().styles
    const [searchParams, setSearchParams] = useSearchParams()
    const [pathList, setPathList] = useState<string[]>([])
    const [vpIndexList, setVpIndexList] = useState<string[]>([])
    const navigate = useNavigate()
    const [loading, setLoading] = useState(false)
    const [fileBucketInfoModalOpen, setFileBucketInfoModalOpen] = useState(false)

    const dir = searchParams.get('dir')
    const virtualPage = searchParams.get('vp')
    const virtualPageIndex = searchParams.get('vpi')

    const setDir = (dir: string) => {
        setSearchParams((prev) => {
            prev.set('dir', dir)
            return prev
        })
    }

    const toggleVirtualPage = (val: boolean) => {
        setSearchParams((prev) => {
            if (val) {
                prev.set('vp', '1')
            } else {
                prev.delete('vp')
            }
            return prev
        })
    }

    useEffect(() => {
        setLoading(true)
        FileBucketApi.pageDirById(fbInfo.id, 1, -1).then(res => {
            setPathList(res.data.records)
            if (searchParams.get('dir') == null && res.data.records[0]) {
                setDir(res.data.records[0])
            }
        }).finally(() => {
            setLoading(false)
        })
    }, [fbInfo]);

    useEffect(() => {
        if (virtualPage == '1' && dir != null && dir != '') {
            setLoading(true)
            let contentTypePrefix: string | undefined;
            for (let type of FbTypes) {
                if (fbInfo.type == type.value) {
                    contentTypePrefix = type.contentTypePrefix
                }
            }
            FileBucketApi.pageVirtualPageIndex(
                fbInfo.id, dir, 1, 20, 3, contentTypePrefix,
            ).then(res => {
                if (res.data.total > 20) { // 结果超过20个，就再查一次，全部查出来
                    FileBucketApi.pageVirtualPageIndex(
                        fbInfo.id, dir, 1, res.data.total, 3, contentTypePrefix,
                    ).then(res => {
                        setVpIndexList(res.data.records)
                    })
                } else {
                    setVpIndexList(res.data.records)
                }
            }).finally(() => {
                setLoading(false)
            })
        }
    }, [virtualPage, fbInfo.type]);

    return (
        <div className={styles.container}>
            <FileBucketInfoModal
                open={fileBucketInfoModalOpen}
                onClose={() => setFileBucketInfoModalOpen(false)}
                fbInfo={fbInfo}
                rerenderTrigger={rerenderTrigger}
            />
            {loading && <Spin fullscreen/>}
            {width > 600 && <>
                <Button type="text"
                        size="large"
                        onClick={() => setFileBucketInfoModalOpen(true)}
                >{fbInfo.name}</Button>
                <div style={{margin: "auto"}}></div>
            </>}
            <Popover
                trigger="click"
                content={
                    vpIndexList.map(item => {
                        let className = styles.popoverBtn
                        if (item == virtualPageIndex) {
                            className += " "
                            className += styles.popoverBtnActive
                        }
                        return (
                            <button
                                className={className}
                                key={item}
                                onClick={() => {
                                    setSearchParams(pre => {
                                        pre.set('vpi', item)
                                        return pre
                                    })
                                }}
                            >
                                {item.substring(fbInfo.rootPath.length)}
                            </button>
                        )
                    })
                }
                classNames={{body: styles.popoverContent}}
            >
                <Button
                    disabled={virtualPage != '1'}
                >虚拟分页</Button>
            </Popover>
            <Switch
                value={virtualPage == "1"}
                onChange={toggleVirtualPage}
            />
            <Popover
                trigger="click"
                content={
                    pathList.map(item => {
                        let className = styles.popoverBtn
                        if (item == dir) {
                            className += " "
                            className += styles.popoverBtnActive
                        }
                        return (
                            <button
                                key={item}
                                className={className}
                                onClick={() => {
                                    setSearchParams(prev => {
                                        prev.delete('vp')
                                        prev.delete('vpi')
                                        prev.set('dir', item)
                                        return prev
                                    })
                                }}
                            >
                                {item.substring(fbInfo.rootPath.lastIndexOf('/'))}
                            </button>
                        )
                    })
                }
                classNames={{body: styles.popoverContent}}
            >
                <Button>选择目录</Button>
            </Popover>
            <Button
                onClick={() => {
                    navigate("/home/content")
                }}
            >返回主页</Button>
        </div>
    )
}

export default BucketHeader
